package org.bees.cms.core.clause;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Transient;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.bees.cms.core.Specific;

@Entity
public class Sorting extends Clause implements Specific<String> {
	private static final long serialVersionUID = 8849597783842970522L;

	private String[] properties;
	private String[] sequences;

	@Override
	public String toSQL(Adapter adapter, Class<?> mapper, String alias) throws Exception {
		StringBuilder builder = new StringBuilder();
		for (int i = 0; properties != null && i < properties.length; i++) {
			if (i == 0) {
				builder.append(" ");
			} else {
				builder.append(",");
			}
			builder.append(adapter.adapt(mapper, properties[i], alias)).append(" ").append(sequences[i]);
		}
		return builder.toString().trim().equals("") ? "" : "ORDER BY" + builder.toString().trim();
	}

	@Transient
	@Column(name = "particular")
	public String[] getProperties() {
		return properties;
	}

	public void setProperties(String[] properties) {
		this.properties = properties;
	}

	@Transient
	@Column(name = "particular")
	public String[] getSequences() {
		return sequences;
	}

	public void setSequences(String[] sequences) {
		this.sequences = sequences;
	}

	@Column(length = 200)
	@Override
	public String getParticular() throws Exception {
		JSONArray array = new JSONArray();
		for (int i = 0; properties != null && i < properties.length; i++) {
			JSONObject object = new JSONObject();
			object.accumulate("property", properties[i]);
			object.accumulate("sequence", sequences[i]);
			array.add(object);
		}
		return array.toString();
	}

	@Override
	public void setParticular(String particular) throws Exception {
		JSONArray array = JSONArray.fromObject(particular);
		properties = new String[array.size()];
		sequences = new String[array.size()];
		for (int i = 0; i < array.size(); i++) {
			JSONObject object = array.getJSONObject(i);
			properties[i] = object.getString("property");
			sequences[i] = object.getString("sequence");
		}
	}

}
